/**
 * Created by BruceLv on 2018/1/22.
 */
import axios from 'axios'
import { Toast } from 'mint-ui'



// 创建axios实例
const service = axios.create({
    //baseURL: 'douban/', // api的base_url
  timeout: 1000 // 请求超时时间
})

service.interceptors.request.use((config) => {
  return config
}, (err) => {
  alert('请求超时')
  return Promise.resolve(err)
})

service.interceptors.response.use((data) => {
  // 数据统一校验处理
  return data
}, (err) => {
  // 数据异常统一处理
  if (err.response.status === 500 || err.response.status === 404 || err.response.status === 504) {
    Toast({
      'message': '服务器挂了',
      'type': 'error'
    })
  } else if (err.response.status === 403) {
    Toast({
      'message': '权限不足,请联系管理员',
      'type': 'error'
    })
  } else {
    Toast({
      'message': '连我都不知道啥问题，好难阿........',
      'type': 'error'
    })
  } 
  return Promise.resolve(err)
})

export function postRequest (url, params) {
  return service({
    method: 'post',
    url: url,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function uploadFileRequest (url, params) {
  return service({
    method: 'post',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export function putRequest (url, params) {
  return service({
    method: 'put',
    url: url,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function deleteRequest (url) {
  return service({
    method: 'delete',
    url: url
  })
}

export function getRequest (url) {
  return service({
    method: 'get',
    url: url
  })
}
